/**
 *  @file : index.js
 *  @brief: 业务模块
 */
define(['network', 'avalon', 'struct', 'jquery.nicescroll', 'xServer', 'xOnline'], function ($, avalon, struct, _, xServer, xOnline) {

  avalon.filters.ustate = function (st) {
    var a = '';
    switch (st) {
      case 0: a = '没有'; break;
      case 1: a = '站立'; break;
      case 2: a = '选座'; break;
      case 3: a = '坐下'; break;
      case 4: a = '同意'; break;
      case 5: a = '旁观'; break;
      case 6: a = '游戏'; break;
      case 7: a = '断线'; break;
      case 8: a = '中途加入'; break;
      case 9: a = '提前开始'; break;
    }
    return '[' + st + ']' + a;
  }

  var vm = avalon.define({
    $id: "app",
    SERVERS: [], // xServer,
    ONLINES: [], // xOnline, // xOnline.slice(0, 3), // xOnline,
    MODE: 0, // 0=表格视图; 1=桌子视图;
    OnTapReqSrvList: function (e) {
      $.ws.send(19, 3); // 请求开服列表
    },
    OnTapReqUsrList: function (e) {
      $.ws.send(19, 5); // 请求在线用户列表
    },
    OnUlistRendered: function (e) {
      console.log('OnUlistRendered');
      $('#ulist2').niceScroll({});
      $('.sec4-2').niceScroll({});
    },
    FillArray: function (attrName, fieldName, arr) {
      var list = this[attrName].toJSON();
      avalon.each(arr, function (a, b) {
        var flag = -1;
        avalon.each(list, function (c, d) {
          if (b[fieldName] == d[fieldName]) {
            flag = c;
            return false;
          }
        });
        if (flag >= 0) {
          list[flag] = b;
        } else {
          list.push(b);
        }
      });
      this[attrName] = list;
    },
    OnTapSwitchView: function () {
      var mode = this.MODE;
      this.MODE = mode ? 0 : 1;
    }
  });
  avalon.scan(document.body);

  $.subscribe('MSG_19_30', function (e, data) { // 获取开服列表数据
    vm.FillArray('SERVERS', 'ServerID', data.data);
  });

  $.subscribe('MSG_19_70', function (e, data) { // 获取在线用户列表数据
    vm.FillArray('ONLINES', 'UserID', data.data);
  });

  $.subscribe('MSG_19_130', function (e, data) { // 用户状态变化
    var stat = data.data[0];
    avalon.each(vm.ONLINES, function (k, v) {
      if (v.UserID == stat.UserID) {
        if (stat.State == 0) {
          vm.ONLINES.removeAt(k);
        } else {
          v.ChairID = stat.ChairID;
          v.TableID = stat.TableID;
          v.GroupID = stat.GroupID;
          v.State = stat.State;
        }
        return false;
      }
    });
  });
  
  $.subscribe('MSG_19_120', function (e, data) { // 更新用户分数
    // console.log('', data);
  });

  $.ws.send(0, 1);
  
});